package service

import (
	"chatroom/message"
	"chatroom/model"
	"chatroom/utils"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{}
var wc = make(map[string]*websocket.Conn)

func WebsocketMessage(c *gin.Context) {
	//升级为websocket
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "系统异常：" + err.Error(),
		})
		return
	}
	defer conn.Close()
	//这个在gin中间件里AuthCheck,设置了
	//userClaims, err := utils.ParseToken(token)
	//c.Set("user_claims", userClaims),所以MustGet可以取到解析好的数据
	uc := c.MustGet("user_claims").(*utils.UserClaims)
	wc[uc.ID] = conn
	fmt.Println("uc", uc, uc.ID, uc.Username)
	for {
		ms := new(message.MessageStruct)
		err := conn.ReadJSON(ms)
		if err != nil {
			log.Printf("Read Error:%v\n", err)
			return
		}
		// 判断用户是否属于消息体的房间
		_, err = model.GetUserRoomByUserIdentityRoomIdentity(uc.ID, ms.RoomIdentity)
		if err != nil {
			log.Printf("UserIdentity:%v RoomIdentity:%v Not Exits\n", uc.ID, ms.RoomIdentity)
			return
		}
		// 保存消息
		mb := &model.MessageBasic{
			UserIdentity: uc.ID,
			RoomIdentity: ms.RoomIdentity,
			Data:         ms.Message,
			CreatedAt:    time.Now().Unix(),
			UpdatedAt:    time.Now().Unix(),
		}
		err = model.InsertOneMessageBasic(mb)
		if err != nil {
			log.Printf("[DB ERROR]:%v\n", err)
			return
		}
		// 获取在特定房间的在线用户
		userRooms, err := model.GetUserRoomByRoomIdentity(ms.RoomIdentity)
		if err != nil {
			log.Printf("[DB ERROR]:%v\n", err)
			return
		}
		for _, room := range userRooms {
			if cc, ok := wc[room.UserIdentity]; ok {
				err := cc.WriteMessage(websocket.TextMessage, []byte(ms.Message))
				if err != nil {
					log.Printf("Write Message Error:%v\n", err)
					return
				}
			}
		}
	}

}
